//
//  ViewController.swift
//  TestYan2
//
//  Created by zhonggu on 15/12/7.
//  Copyright © 2015年 zhonggu. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    private lazy var filter: CIFilter? = {
        
        let coreImage = CIImage(image: UIImage(named: "test")!)?.imageByClampingToExtent()
        let rippleTransitionFilter = CIFilter(name: "CIRippleTransition")
        rippleTransitionFilter!.setValue(coreImage, forKey: kCIInputImageKey)
        rippleTransitionFilter!.setValue(coreImage, forKey: kCIInputTargetImageKey)
        rippleTransitionFilter!.setValue(CIImage(), forKey: kCIInputShadingImageKey)
        return rippleTransitionFilter
        
    }()
    
    private lazy var originalImageExtent: CGRect? = {
        return CIImage(image: UIImage(named: "test")!)?.extent
    }()
    
    private var duration = 5.0
    private var transitionStartTime = CACurrentMediaTime()
    private var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        imageView = UIImageView(image: UIImage(named: "test"))
        imageView.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.size.width, height: UIScreen.mainScreen().bounds.size.height);
        self.view.addSubview(imageView)
        
        rippleImage(5.0)
        
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    func rippleImage(duration: Double) {
        guard let _ = filter else {
            return
        }
        self.duration = duration
        transitionStartTime = CACurrentMediaTime()
        let displayLink = CADisplayLink(target: self, selector: "timerFired:")
        displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
    }
//    var progress = 0.0
    func timerFired(displayLink: CADisplayLink) {
        guard let filter = filter, extent = originalImageExtent else {
            displayLink.invalidate()
            return
        }
        
        let progress = max((CACurrentMediaTime() - transitionStartTime) / duration, 1.0)
        filter.setValue(progress, forKey: kCIInputTimeKey)
        imageView.image = UIImage(CIImage: filter.outputImage!.imageByCroppingToRect(extent))
        print(progress)
        if progress == 5.0 {
//            imageView.image = UIImage(CIImage: originalCoreImage)
            displayLink.invalidate()
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

